package com.bringspring.system.permission.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bringspring.common.base.*;
import com.bringspring.common.base.vo.DownloadVO;
import com.bringspring.common.base.vo.ListVO;
import com.bringspring.common.base.vo.PageListVO;
import com.bringspring.common.base.vo.PaginationVO;
import com.bringspring.common.config.ConfigValueUtil;
import com.bringspring.common.constant.MsgCode;
import com.bringspring.common.exception.DataException;
import com.bringspring.common.util.*;
import com.bringspring.common.util.enums.FileTypeEnum;
import com.bringspring.common.util.file.UploadUtil;
import com.bringspring.common.util.treeutil.SumTree;
import com.bringspring.common.util.treeutil.newtreeutil.TreeDotUtils;
import com.bringspring.system.base.exception.BaseException;
import com.bringspring.system.base.util.JsonUtilEx;
import com.bringspring.system.base.util.RemoveUtil;
import com.bringspring.system.permission.constant.PermissionConst;
import com.bringspring.system.permission.entity.*;
import com.bringspring.system.permission.exception.PermissionException;
import com.bringspring.system.permission.model.permission.PermissionModel;
import com.bringspring.system.permission.model.user.form.UserCrForm;
import com.bringspring.system.permission.model.user.form.UserResetPasswordForm;
import com.bringspring.system.permission.model.user.form.UserUpForm;
import com.bringspring.system.permission.model.user.mod.UserByRoleModel;
import com.bringspring.system.permission.model.user.mod.UserIdModel;
import com.bringspring.system.permission.model.user.mod.UserSelectorModel;
import com.bringspring.system.permission.model.user.mod.UsersByPositionModel;
import com.bringspring.system.permission.model.user.page.PageUser;
import com.bringspring.system.permission.model.user.page.PaginationUser;
import com.bringspring.system.permission.model.user.vo.*;
import com.bringspring.system.permission.service.*;
import com.bringspring.system.permission.util.BaseDataUtil;
import com.bringspring.system.permission.util.PermissionUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;

/**
 * 用户管理
 *
 * @author 开发平台组
 * @version V1.0.0
 * @copyright 股份有限公司
 * @date 2017年9月26日 上午9:18
 */
@Api(tags = "用户管理", value = "Users")
@Slf4j
@RestController
@RequestMapping("/api/permission/Users")
public class UserController {

    @Autowired
    private CacheKeyUtil cacheKeyUtil;
    @Autowired
    private ConfigValueUtil configValueUtil;

    /*=== the same ===*/

    @Autowired
    private UserService userService;
    @Autowired
    private UserProvider userProvider;
    @Autowired
    private OrganizeService organizeService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private UserRelationService userRelationService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private OrganizeRelationService organizeRelationService;
    @Autowired
    private PositionService positionService;

    @Autowired
    private BaseDataUtil baseDataUtil;


    /**
     * 取出线程池
     */
    @Autowired
    private Executor threadPoolExecutor;

    /**
     * 获取用户列表
     *
     * @param pagination 分页参数
     * @return ignore
     */
    @ApiOperation("获取用户列表")
    @GetMapping
    public ActionResult<PageListVO<UserListVO>> getList(PaginationUser pagination) {
        UserInfo userInfo = userProvider.get();
        List<UserEntity> userList = userService.getList(pagination, pagination.getOrganizeId(), false);
        List<UserListVO> list = new ArrayList<>();
        for (UserEntity userEntity : userList) {
            UserListVO userVO = JsonUtil.getJsonToBean(userEntity, UserListVO.class);
            // 时间小于当前时间则判断已解锁
            if (userVO.getEnabledMark() != 0) {
                if (Objects.nonNull(userEntity.getUnlockTime()) && userEntity.getUnlockTime().getTime() > System.currentTimeMillis()) {
                    userVO.setEnabledMark(2);
                }

            }
            //获取组织
            String organizeStr = userRelationService.getAllOrganizeNameInfoById(userEntity.getId());

            userVO.setOrganize(organizeStr);
            list.add(userVO);
        }

        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
    }

    /**
     * 获取用户列表
     *
     * @param pagination 分页参数
     * @return ignore
     */
    @ApiOperation("获取用户列表")
    @GetMapping("/getAuditList")
    public ActionResult<PageListVO<UserListVO>> getAuditList(PaginationUser pagination) throws BaseException {
        List<UserListVO> auditList = userService.getAuditList(pagination);
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(auditList, paginationVO);
    }

    /**
     * 员工管理根据权限获取用户列表
     *
     * @param pagination 分页参数
     * @return ignore
     */
    @ApiOperation("员工管理根据权限获取用户列表")
    @PostMapping("/UserJurisdiction")
    public ActionResult<PageListVO<UserListVO>> getJurisDictionList(@RequestBody @Valid PaginationUser pagination) {
        UserInfo userInfo = userProvider.get();
        List<UserEntity> userList = userService.getJurisDictionList(pagination);
        List<UserListVO> list = new ArrayList<>();
        for (UserEntity userEntity : userList) {
            UserListVO userVO = JsonUtil.getJsonToBean(userEntity, UserListVO.class);
            if (StringUtils.isNotEmpty(pagination.getOrganizeId())){
                // 时间小于当前时间则判断已解锁
                if (userVO.getEnabledMark() != 0) {
                    if (Objects.nonNull(userEntity.getUnlockTime()) && userEntity.getUnlockTime().getTime() > System.currentTimeMillis()) {
                        userVO.setEnabledMark(2);
                    }

                }
                //获取组织
                String organizeStr = userRelationService.getAllOrganizeNameInfoById(userEntity.getId());
                userVO.setOrganize(organizeStr);
                list.add(userVO);
            }
        }

        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
    }

    /**
     * 区域授权获取用户列表
     *
     * @param pagination 分页参数
     * @return ignore
     */
    @GetMapping("/authorizeAddressGetList")
    public ActionResult<PageListVO<UserListVO>> authorizeAddressGetList(PaginationUser pagination) {
        UserInfo userInfo = userProvider.get();
        List<UserEntity> userList = userService.authorizeAddressGetList(pagination, pagination.getOrganizeId(), false);
        List<UserListVO> list = new ArrayList<>();
        for (UserEntity userEntity : userList) {
            //获取该用户组织id与当前登录用户做比对！
            if(ObjectUtil.isNotEmpty(pagination.getAlreadyAuthorize())){
                //联表查询用户授权区域
                List<UserRelationEntity> arealist = userRelationService.list(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, userEntity.getId()));
                if (ObjectUtil.isNotEmpty(arealist)) {
                    List<String> collect = arealist.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());
                    List<String> addressList = new ArrayList<>();
                    for (String s : collect) {
                        addressList.add(baseDataUtil.provinceData(s));

                    }
                    userEntity.setAddressList(StringUtils.join(addressList, ","));
                }
            }

            //判断当前角色是否是销售主管,并进行排序
            if (userEntity.getRoleId().contains("361808523769679237")) {
                userEntity.setAreaManagerFlag("0");
            }else {
                userEntity.setAreaManagerFlag("1");
            }


            UserListVO userVO = JsonUtil.getJsonToBean(userEntity, UserListVO.class);
            // 时间小于当前时间则判断已解锁
            if (userVO.getEnabledMark() != 0) {
                if (Objects.nonNull(userEntity.getUnlockTime()) && userEntity.getUnlockTime().getTime() > System.currentTimeMillis()) {
                    userVO.setEnabledMark(2);
                }

            }
            //获取组织1
            // 获取组织
            String organizeStr = userRelationService.getAllOrganizeNameInfoById(userEntity.getId());

            userVO.setOrganize(organizeStr);
            list.add(userVO);
        }
        //如果是授权页面则进行排序
        if(ObjectUtil.isNotEmpty(pagination.getAlreadyAuthorize())){
            if (ObjectUtil.isNotEmpty(pagination.getAlreadyAuthorize()) && ObjectUtil.isNotEmpty(list)) {
                list = list.stream().sorted(Comparator.comparing(UserListVO::getAreaManagerFlag)).collect(Collectors.toList());
            }
        }

        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
    }

    /**
     * 获取用户列表
     *
     * @return ignore
     */
    @ApiOperation("获取所有用户列表")
    @GetMapping("/All")
    public ActionResult<ListVO<UserAllVO>> getAllUsers(Pagination pagination) {
        List<UserEntity> list = userService.getList(pagination, null, false);
        List<UserAllVO> user = JsonUtil.getJsonToList(list, UserAllVO.class);
        ListVO<UserAllVO> vo = new ListVO<>();
        vo.setList(user);
        return ActionResult.success(vo);
    }

    /**
     * IM通讯获取用户接口
     *
     * @param pagination 分页参数
     * @return ignore
     */
    @ApiOperation("IM通讯获取用户")
    @GetMapping("/ImUser")
    public ActionResult<PageListVO<ImUserListVo>> getAllImUserUsers(Pagination pagination) {
        List<UserEntity> data = userService.getList(pagination, null, true);
        List<ImUserListVo> list = new ArrayList<>();
        List<OrganizeEntity> organizeList = organizeService.getOrganizeName(data.stream().map(t -> t.getOrganizeId()).collect(Collectors.toList()));
        for (UserEntity entity : data) {
            ImUserListVo user = JsonUtil.getJsonToBean(entity, ImUserListVo.class);
            OrganizeEntity organize = organizeList.stream().filter(t -> t.getId().equals(entity.getOrganizeId())).findFirst().orElse(null);
            user.setDepartment(organize != null ? organize.getFullName() : "");
//            user.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
            user.setHeadIcon(entity.getHeadIcon());
            list.add(user);
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(list, paginationVO);
    }

    /**
     * 获取用户下拉框列表
     *
     * @return ignore
     */
    @ApiOperation("获取用户下拉框列表")
    @GetMapping("/Selector")
    public ActionResult<ListVO<UserSelectorVO>> selector() {
        List<OrganizeEntity> allOrganizeData = organizeService.getList();
        List<OrganizeEntity> organizeData = organizeService.getList().stream().filter(
                t -> "1".equals(String.valueOf(t.getEnabledMark()))
        ).collect(Collectors.toList());
        List<UserEntity> userData = userService.getList().stream().filter(
                t -> "1".equals(String.valueOf(t.getEnabledMark()))
        ).collect(Collectors.toList());
        List<UserSelectorModel> treeList = JsonUtil.getJsonToList(organizeData, UserSelectorModel.class);
        for (UserSelectorModel entity1 : treeList) {
            if ("department".equals(entity1.getType())) {
                entity1.setIcon("icon-ym icon-ym-tree-department1");
            } else if (PermissionConst.COMPANY.equals(entity1.getType())) {
                entity1.setIcon("icon-ym icon-ym-tree-organization3");
            }
        }
        for (UserEntity entity : userData) {
            UserSelectorModel treeModel = new UserSelectorModel();
            treeModel.setId(entity.getId());
            treeModel.setParentId(entity.getOrganizeId());
            treeModel.setFullName(entity.getRealName() );
            treeModel.setType("user");
            treeModel.setIcon("icon-ym icon-ym-tree-user2");
            treeList.add(treeModel);
        }
        List<SumTree<UserSelectorModel>> trees = TreeDotUtils.convertListToTreeDot(treeList);
        List<UserSelectorVO> listvo = JsonUtil.getJsonToList(trees, UserSelectorVO.class);
        List<OrganizeEntity> entities = allOrganizeData.stream().filter(
                t -> "1".equals(String.valueOf(t.getEnabledMark())) && "-1".equals(t.getParentId())
        ).collect(Collectors.toList());
        Iterator<UserSelectorVO> iterator = listvo.iterator();
        while (iterator.hasNext()) {
            UserSelectorVO userSelectorVO = iterator.next();
            for (OrganizeEntity entity : entities) {
                if (entity.getId().equals(userSelectorVO.getParentId())) {
                    iterator.remove();//使用迭代器的删除方法删除
                }
            }
        }
        ListVO<UserSelectorVO> vo = new ListVO<>();
        vo.setList(listvo);
        return ActionResult.success(vo);
    }

    /**
     * 获取用户下拉框列表
     *
     * @return
     */
    @ApiOperation("获取用户下拉框列表")
    @PostMapping("/ImUser/Selector/{organizeId}")
    public ActionResult<ListVO<UserSelectorVO>> imUserSelector(@PathVariable("organizeId") String organizeIdForm, @RequestBody Page page) {
        String organizeId = XSSEscape.escape(organizeIdForm);
        List<UserSelectorVO> jsonToList = new ArrayList<>();
        //判断是否搜索关键字
        if (StringUtils.isNotEmpty(page.getKeyword())) {
            //通过关键字查询
            List<UserEntity> list = userService.getList(page.getKeyword());
            //遍历用户给要返回的值插入值
            for (UserEntity entity : list) {
                UserSelectorVO vo = JsonUtil.getJsonToBean(entity, UserSelectorVO.class);
                vo.setId(entity.getId());
                vo.setParentId(entity.getOrganizeId());
                vo.setFullName(entity.getRealName() );
                vo.setType("user");
                vo.setIcon("icon-ym icon-ym-tree-user2");
                vo.setHasChildren(false);
                vo.setIsLeaf(true);
                vo.setEnabledMark(1);
                jsonToList.add(vo);
            }
            ListVO<UserSelectorVO> vo = new ListVO<>();
            vo.setList(jsonToList);
            return ActionResult.success(vo);
        }
        //获取所有组织
        List<OrganizeEntity> collect = organizeService.getList().stream().filter(t -> t.getEnabledMark() == 1).collect(Collectors.toList());
        //判断时候传入组织id
        //如果传入组织id，则取出对应的子集
        if (!"0".equals(organizeId)) {
            //通过组织查询部门及人员
            //单个组织
            List<OrganizeEntity> list = collect.stream().filter(t -> organizeId.equals(t.getId())).collect(Collectors.toList());
            if (list.size() > 0) {
                //获取组织信息
                OrganizeEntity organizeEntity = list.get(0);
                //取出组织下的部门
                List<OrganizeEntity> collect1 = collect.stream().filter(t -> t.getParentId().equals(organizeEntity.getId())).collect(Collectors.toList());
                for (OrganizeEntity entitys : collect1) {
                    UserSelectorVO vo = JsonUtil.getJsonToBean(entitys, UserSelectorVO.class);
                    if ("department".equals(entitys.getCategory())) {
                        vo.setIcon("icon-ym icon-ym-tree-department1");
                    } else if (PermissionConst.COMPANY.equals(entitys.getCategory())) {
                        vo.setIcon("icon-ym icon-ym-tree-organization3");
                    }
                    // 判断组织下是否有人
                    jsonToList.add(vo);
                    vo.setHasChildren(true);
                    vo.setIsLeaf(false);
                }
                //取出组织下的人员
                List<UserEntity> entityList = userService.getListByOrganizeId(organizeId, null);
                for (UserEntity entity : entityList) {
                    if ("0".equals(String.valueOf(entity.getEnabledMark()))) {
                        continue;
                    }
                    UserSelectorVO vo = JsonUtil.getJsonToBean(entity, UserSelectorVO.class);
                    vo.setId(entity.getId());
                    vo.setParentId(organizeId);
                    vo.setFullName(entity.getRealName() );
                    vo.setType("user");
                    vo.setIcon("icon-ym icon-ym-tree-user2");
                    vo.setHasChildren(false);
                    vo.setIsLeaf(true);
                    vo.setEnabledMark(1);
                    jsonToList.add(vo);
                }
            }
            ListVO<UserSelectorVO> vo = new ListVO<>();
            vo.setList(jsonToList);
            return ActionResult.success(vo);
        }

        //如果没有组织id，则取出所有组织
        List<OrganizeEntity> organizeEntityList = collect.stream().filter(t -> "-1".equals(t.getParentId())).collect(Collectors.toList());
        jsonToList = JsonUtil.getJsonToList(organizeEntityList, UserSelectorVO.class);
        //添加图标
        for (UserSelectorVO userSelectorVO : jsonToList) {
            userSelectorVO.setIcon("icon-ym icon-ym-tree-organization3");
            userSelectorVO.setHasChildren(true);
            userSelectorVO.setIsLeaf(false);
        }
        ListVO<UserSelectorVO> vo = new ListVO<>();
        vo.setList(jsonToList);
        return ActionResult.success(vo);
    }

    /**
     * 获取用户信息
     *
     * @param id 用户id
     * @return ignore
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/{id}")
    public ActionResult<UserInfoVO> getInfo(@PathVariable("id") String id) throws DataException {
        UserEntity entity = userService.getInfo(id);
        if (entity == null) {
            return ActionResult.fail("用户不存在");
        }
        //联表查询用户授权区域
        List<UserRelationEntity> arealist = userRelationService.list(Wrappers.<UserRelationEntity>lambdaQuery().eq(UserRelationEntity::getObjectType, "Area").eq(UserRelationEntity::getUserId, entity.getId()));
        //存储集合地址
        List<List<String>> addrList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(arealist)) {
            List<String> collect = arealist.stream().map(UserRelationEntity::getObjectId).collect(Collectors.toList());

            collect.stream().forEach(item -> {
                List<String> stringList = new ArrayList<>();
                String[] split = item.replace("[", "").replace("]", "").replaceAll("\"", "").split(",");

                stringList.addAll(Arrays.asList(split));
                addrList.add(stringList);
            });
        }

        QueryWrapper<UserRelationEntity> roleQuery = new QueryWrapper<>();
        roleQuery.lambda().eq(UserRelationEntity::getUserId, id);
        roleQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ROLE);
        List<String> roleIdList = new ArrayList<>();
        for (UserRelationEntity ure : userRelationService.list(roleQuery)) {
            roleIdList.add(ure.getObjectId());
        }

//        entity.setHeadIcon(UploaderUtil.uploaderImg(entity.getHeadIcon()));
//      OrganizeEntity info = organizeService.getInfo(entity.getOrganizeId());
        // 得到组织树
        UserInfoVO vo = JsonUtilEx.getJsonToBeanEx(entity, UserInfoVO.class);
        vo.setRoleId(String.join(",", roleIdList));


        // 获取组织id数组
        QueryWrapper<UserRelationEntity> query = new QueryWrapper<>();
        query.lambda().eq(UserRelationEntity::getUserId, id);
        query.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.ORGANIZE);
        List<String> organizeIds = new ArrayList<>();
        userRelationService.list(query).forEach(u -> {
            organizeIds.add(u.getObjectId());
        });

        // 岗位装配
        QueryWrapper<UserRelationEntity> positionQuery = new QueryWrapper<>();
        positionQuery.lambda().eq(UserRelationEntity::getUserId, id);
        positionQuery.lambda().eq(UserRelationEntity::getObjectType, PermissionConst.POSITION);
        String positionIds = "";
        for (UserRelationEntity ure : userRelationService.list(positionQuery)) {
            PositionEntity info = positionService.getInfo(ure.getObjectId());
            if (info != null) {
                positionIds = positionIds + "," + ure.getObjectId();
            }
        }
        if (positionIds.length() > 0) {
            vo.setPositionId(positionIds.substring(1));
        } else {
            vo.setPositionId(null);
        }
        // 设置分组id
        List<UserRelationEntity> listByObjectType = userRelationService.getListByObjectType(entity.getId(), PermissionConst.GROUP);
        StringBuilder groupId = new StringBuilder();
        listByObjectType.stream().forEach(t -> groupId.append("," + t.getObjectId()));
        if (groupId.length() > 0) {
            vo.setGroupId(groupId.toString().replaceFirst(",", ""));
        }
        vo.setOrganizeIdTree(PermissionUtil.getOrgIdsTree(organizeIds, 1, organizeService));

        String majorOrgId = entity.getOrganizeId();
        List<PermissionModel> permissionModels = userRelationService.setModel(organizeService.getOrgEntityList(organizeIds, false), majorOrgId);
        permissionModels.forEach(p -> p.setFullName(PermissionUtil.getLinkInfoByOrgId(p.getId(), organizeService, true)));
        vo.setOrganizeNames(permissionModels);
        vo.setAuthorizeAddress(addrList);
        return ActionResult.success(vo);
    }


    /**
     * 获取用户简单信息
     *
     * @param id 用户id
     * @return ignore
     */
    @ApiOperation("获取用户信息")
    @GetMapping("/getSimpleInfo/{id}")
    public ActionResult<UserEntity> getSimpleInfo(@PathVariable("id") String id) throws DataException {
        UserEntity info = userService.getInfo(id);
        return ActionResult.success(info);
    }

    ;

    /**
     * 新建用户
     *
     * @param userCrForm 表单参数
     */
    
    @ApiOperation("新建用户")
    @PostMapping
    public ActionResult<String> create(@RequestBody @Valid UserCrForm userCrForm) throws Exception {
        UserEntity entity = JsonUtil.getJsonToBean(userCrForm, UserEntity.class);

        userService.create(entity);

        return ActionResult.success(MsgCode.SU001.get());
    }

    /**
     * 修改用户
     *
     * @param userUpForm 表单参数
     * @param id         主键值
     */
    
    @ApiOperation("修改用户")
    @PutMapping("/{id}")
    public ActionResult<String> update(@PathVariable("id") String id, @RequestBody @Valid UserUpForm userUpForm) throws Exception {
        UserEntity entity = JsonUtil.getJsonToBean(userUpForm, UserEntity.class);

        boolean flag = userService.update(id, entity);

        if (!flag) {
            return ActionResult.fail(MsgCode.FA002.get());
        }
        return ActionResult.success(MsgCode.SU004.get());
    }

    /**
     * 删除用户
     *
     * @param id 主键值
     * @return ignore
     */
    
    @ApiOperation("删除用户")
    @DeleteMapping("/{id}")
    public ActionResult<String> delete(@PathVariable("id") String id) throws Exception {
        UserEntity entity = userService.getInfo(id);
        if (entity != null) {
            userService.delete(entity);
            return ActionResult.success(MsgCode.SU003.get());
        }
        return ActionResult.fail(MsgCode.FA003.get());
    }


    /**
     * 修改用户密码
     *
     * @return ignore
     */
    
    @ApiOperation("修改用户密码")
    @PostMapping("/{id}/Actions/ResetPassword")
    public ActionResult<String> modifyPassword(@PathVariable("id") String id, @RequestBody @Valid UserResetPasswordForm userResetPasswordForm) {
        UserEntity entity = userService.getInfo(id);
        if (entity != null) {
            entity.setPassword(userResetPasswordForm.getUserPassword());
            userService.updatePassword(entity);
            userProvider.removeOnLine(entity.getId());
            RemoveUtil.removeOnline(entity.getId());
            return ActionResult.success(MsgCode.SU005.get());
        }
        return ActionResult.success("操作失败,用户不存在");
    }

    /**
     * 更新用户状态
     *
     * @param id 主键值
     * @return ignore
     */
    @ApiOperation("更新用户状态")
    @PutMapping("/{id}/Actions/State")
    public ActionResult<String> disable(@PathVariable("id") String id) throws Exception {
        UserEntity entity = userService.getInfo(id);
        if (entity != null) {
            if ("1".equals(String.valueOf(entity.getIsAdministrator()))) {
                return ActionResult.fail("无法修改管理员账户状态");
            }
            if (entity.getEnabledMark() != null) {
                if ("1".equals(String.valueOf(entity.getEnabledMark()))) {
                    entity.setEnabledMark(0);
                    userProvider.removeOnLine(entity.getId());
                    RemoveUtil.removeOnline(entity.getId());
                    userService.update(id, entity);
                } else {
                    entity.setEnabledMark(1);
                    userService.update(id, entity);
                }
            } else {
                entity.setEnabledMark(1);
                userService.update(id, entity);
            }
            return ActionResult.success(MsgCode.SU005.get());
        }
        return ActionResult.success("操作失败,用户不存在");
    }

    /**
     * 解除锁定
     *
     * @param id 主键值
     * @return ignore
     */
    @ApiOperation("解除锁定")
    @PutMapping("/{id}/Actions/unlock")
    public ActionResult<String> unlock(@PathVariable("id") String id) throws Exception {
        UserEntity entity = userService.getInfo(id);
        if (entity != null) {
            // 状态变成正常
            entity.setEnabledMark(1);
            entity.setUnlockTime(null);
            entity.setLogErrorCount(0);
            entity.setId(id);
            userService.updateById(entity);
            return ActionResult.success(MsgCode.SU005.get());
        }
        return ActionResult.success("操作失败,用户不存在");
    }

    /**
     * 获取用户基本信息
     *
     * @param userIdModel 用户id
     * @return ignore
     */
    @ApiOperation("获取用户基本信息")
    @PostMapping("/getUserList")
    public ActionResult<ListVO<UserIdListVo>> getUserList(@RequestBody UserIdModel userIdModel) {
        List<UserIdListVo> list = new ArrayList<>();
        for (String userId : userIdModel.getUserId()) {
            UserEntity entity = userService.getInfo(userId);
            if (entity == null) {
                continue;
            }
            // 如果被禁用
            if ("0".equals(String.valueOf(entity.getEnabledMark()))) {
                continue;
            }
            UserIdListVo vo = JsonUtil.getJsonToBean(entity, UserIdListVo.class);
            vo.setFullName(entity.getRealName());
            list.add(vo);
        }
        ListVO<UserIdListVo> listVO = new ListVO<>();
        listVO.setList(list);
        return ActionResult.success(listVO);
    }

    /**
     * 获取组织下的人员
     *
     * @param page 页面信息
     * @return ignore
     */
    @ApiOperation("获取组织下的人员")
    @GetMapping("/getOrganization")
    public ActionResult getOrganization(PageUser page) {
        String departmentId = page.getOrganizeId();
        // 判断是否获取当前组织下的人员
        if ("0".equals(departmentId)) {
            departmentId = userProvider.get().getDepartmentId();
            // 为空则取组织id
            if (StringUtils.isEmpty(departmentId)) {
                departmentId = userProvider.get().getOrganizeId();
            }
        }
        List<UserEntity> list = userService.getListByOrganizeId(departmentId, page.getKeyword());
        for (UserEntity entity : list) {
            entity.setRealName(entity.getRealName() );
        }
        List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class);
        return ActionResult.success(jsonToList);
    }

    /**
     * 获取岗位人员
     *
     * @param page 页面信息
     * @return ignore
     */
    @ApiOperation("获取岗位人员")
    @GetMapping("/GetUsersByPositionId")
    public ActionResult<List<UserByRoleVO>> getUsersByPositionId(UsersByPositionModel page) {
        List<UserByRoleVO> list = new ArrayList<>(1);
        String keyword = page.getKeyword();
        // 岗位id
        String positionId = page.getPositionId();
        // 得到关联的组织id
        List<OrganizeRelationEntity> relationListByObjectIdAndType = organizeRelationService.getRelationListByObjectIdAndType(PermissionConst.POSITION, positionId);
        if (relationListByObjectIdAndType.size() == 1) {
            UserByRoleVO vo = new UserByRoleVO();
            String organizeId = relationListByObjectIdAndType.get(0).getOrganizeId();
            // 得到组织信息
            OrganizeEntity organizeEntity = organizeService.getInfo(organizeId);
            if (Objects.nonNull(organizeEntity)) {
                vo.setId(organizeEntity.getId());
                vo.setType(organizeEntity.getCategory());
                if ("department".equals(organizeEntity.getCategory())) {
                    vo.setIcon("icon-ym icon-ym-tree-department1");
                } else {
                    vo.setIcon("icon-ym icon-ym-tree-organization3");
                }
                vo.setEnabledMark(organizeEntity.getEnabledMark());
                // 组装组织名称
                String orgName = organizeService.getFullNameByOrgIdTree(organizeEntity.getOrganizeIdTree(), "/");
                vo.setFullName(orgName);
                // 赋予子集
                List<UserByRoleVO> userByRoleVOS = new ArrayList<>(16);
                List<UserEntity> lists = userService.getListByOrganizeId(organizeEntity.getId(), keyword);
                if (lists.size() > 0) {
                    vo.setHasChildren(true);
                    vo.setIsLeaf(false);
                    lists.stream().forEach(t -> {
                        UserByRoleVO userByRoleVO = new UserByRoleVO();
                        userByRoleVO.setParentId(organizeEntity.getId());
                        userByRoleVO.setId(t.getId());
                        userByRoleVO.setFullName(t.getRealName());
                        userByRoleVO.setEnabledMark(t.getEnabledMark());
                        userByRoleVO.setIsLeaf(true);
                        userByRoleVO.setHasChildren(false);
                        userByRoleVO.setIcon("icon-ym icon-ym-tree-user2");
                        userByRoleVO.setType("user");
                        userByRoleVOS.add(userByRoleVO);
                    });
                    vo.setChildren(userByRoleVOS);
                } else {
                    vo.setHasChildren(false);
                    vo.setIsLeaf(true);
                    vo.setChildren(new ArrayList<>());
                }
                list.add(vo);
            }
        }
        return ActionResult.success(list);
    }

    /**
     * 角色成员弹窗
     *
     * @param model
     * @return ignore
     */
    @ApiOperation("角色成员弹窗")
    @GetMapping("/GetUsersByRoleOrgId")
    public ActionResult<List<UserByRoleVO>> getUsersByRoleOrgId(UserByRoleModel model) {
        List<UserByRoleVO> jsonToList = new ArrayList<>(16);
        // 得到组织关系
        List<OrganizeRelationEntity> relationListByRoleId = organizeRelationService.getRelationListByRoleId(model.getRoleId());
        // 得到组织信息
        List<OrganizeEntity> orgEntityList = organizeService.getOrgEntityList(relationListByRoleId.stream().map(OrganizeRelationEntity::getOrganizeId).collect(Collectors.toList()), true);
        //判断是否搜索关键字
        if (StringUtils.isNotEmpty(model.getKeyword())) {
            //通过关键字查询
            List<UserEntity> list = userService.getList(orgEntityList.stream().map(OrganizeEntity::getId).collect(Collectors.toList()), model.getKeyword());
            //遍历用户给要返回的值插入值
            for (UserEntity entity : list) {
                UserByRoleVO vo = new UserByRoleVO();
                vo.setId(entity.getId());
                vo.setFullName(entity.getRealName() );
                vo.setEnabledMark(entity.getEnabledMark());
                vo.setIsLeaf(true);
                vo.setHasChildren(false);
                vo.setIcon("icon-ym icon-ym-tree-user2");
                vo.setType("user");
                jsonToList.add(vo);
            }
            return ActionResult.success(jsonToList);
        }
        //获取所有组织
        List<OrganizeEntity> collect = organizeService.getList().stream().filter(t -> t.getEnabledMark() == 1).collect(Collectors.toList());
        //判断时候传入组织id
        //如果传入组织id，则取出对应的子集
        if (!"0".equals(model.getOrganizeId())) {
            //通过组织查询部门及人员
            //单个组织
            List<OrganizeEntity> list = collect.stream().filter(t -> model.getOrganizeId().equals(t.getId())).collect(Collectors.toList());
            if (list.size() > 0) {
                //获取组织信息
                OrganizeEntity organizeEntity = list.get(0);
                //取出组织下的部门
                List<OrganizeEntity> collect1 = collect.stream().filter(t -> t.getParentId().equals(organizeEntity.getId())).collect(Collectors.toList());
                // 判断组织关系中是否有子部门id
                List<OrganizeEntity> organizeEntities = new ArrayList<>();
                for (OrganizeEntity entity : collect1) {
                    List<OrganizeRelationEntity> collect2 = relationListByRoleId.stream().filter(t -> entity.getId().equals(t.getOrganizeId())).collect(Collectors.toList());
                    collect2.stream().forEach(t -> {
                        if (StringUtils.isNotEmpty(t.getOrganizeId())) {
                            organizeEntities.add(organizeService.getInfo(t.getOrganizeId()));
                        }
                    });
                }
                // 其他不是子集的直接显示
                List<OrganizeRelationEntity> collect2 = relationListByRoleId.stream()
                        .filter(item -> !organizeEntities.stream().map(e -> e.getId())
                                .collect(Collectors.toList()).contains(item.getOrganizeId()))
                        .collect(Collectors.toList());
                // 移除掉上级不是同一个的
                List<OrganizeRelationEntity> collect3 = collect2.stream().filter(t -> !organizeService.getInfo(t.getOrganizeId()).getOrganizeIdTree().contains(model.getOrganizeId())).collect(Collectors.toList());
                collect2.removeAll(collect3);
                List<OrganizeRelationEntity> collect4 = collect2.stream().filter(t -> !t.getOrganizeId().equals(model.getOrganizeId())).collect(Collectors.toList());
                List<OrganizeEntity> collect5 = collect.stream().filter(x -> collect4.stream().map(d -> d.getOrganizeId()).collect(Collectors.toList()).contains(x.getId())).collect(Collectors.toList());
                List<OrganizeEntity> organizeEntities1 = new ArrayList<>(collect5);
                // 不是子集的对比子集的
                for (OrganizeEntity entity : collect5) {
                    for (OrganizeEntity organizeEntity1 : organizeEntities) {
                        if (entity.getOrganizeIdTree().contains(organizeEntity1.getId())) {
                            organizeEntities1.remove(entity);
                        }
                    }
                }

                //取出组织下的人员
                List<UserEntity> entityList = userService.getListByOrganizeId(model.getOrganizeId(), null);
                for (UserEntity entity : entityList) {
                    UserByRoleVO vo = new UserByRoleVO();
                    vo.setId(entity.getId());
                    vo.setFullName(entity.getRealName() );
                    vo.setEnabledMark(entity.getEnabledMark());
                    vo.setIsLeaf(true);
                    vo.setHasChildren(false);
                    vo.setIcon("icon-ym icon-ym-tree-user2");
                    vo.setType("user");
                    jsonToList.add(vo);
                }
                // 处理子集断层
                // 断层拥有同一层的话，需要合并
                List<OrganizeEntity> organizeEntities2 = new ArrayList<>(collect5);
                for (OrganizeEntity entity : organizeEntities2) {
                    List<OrganizeEntity> collect6 = organizeEntities2.stream().filter(t -> !entity.getId().equals(t.getId()) && t.getOrganizeIdTree().contains(entity.getOrganizeIdTree())).collect(Collectors.toList());
                    organizeEntities1.removeAll(collect6);
                }

                for (OrganizeEntity entity : organizeEntities1) {
                    StringBuffer stringBuffer = new StringBuffer();
                    String[] split = entity.getOrganizeIdTree().split(",");
                    List<String> list1 = Arrays.asList(split);
                    List<String> list2 = new ArrayList<>(list1);
                    int indexOf = list2.indexOf(model.getOrganizeId());
                    while (indexOf >= 0) {
                        list2.remove(indexOf);
                        indexOf--;
                    }
                    StringBuffer organizeIdTree = new StringBuffer();
                    for (String parentId : list2) {
                        OrganizeEntity organizes = organizeService.getInfo(parentId);
                        if (Objects.nonNull(organizes) && StringUtils.isNotEmpty(organizes.getFullName())) {
                            organizeIdTree.append("/" + organizes.getFullName());
                        }
                    }
                    String toString = organizeIdTree.toString();
                    if (StringUtils.isNotEmpty(toString)) {
                        String organizeId = toString.replaceFirst("/", "");
                        stringBuffer.append("," + organizeId);
                    }
                    UserByRoleVO userByRoleVO = new UserByRoleVO();
                    userByRoleVO.setId(entity.getId());
                    userByRoleVO.setType(entity.getCategory());
                    userByRoleVO.setFullName(stringBuffer.toString().replace(",", ""));
                    if ("department".equals(entity.getCategory())) {
                        userByRoleVO.setIcon("icon-ym icon-ym-tree-department1");
                    } else {
                        userByRoleVO.setIcon("icon-ym icon-ym-tree-organization3");
                    }
                    userByRoleVO.setHasChildren(true);
                    userByRoleVO.setIsLeaf(false);
                    userByRoleVO.setEnabledMark(entity.getEnabledMark());
                    jsonToList.add(userByRoleVO);
                }
                for (OrganizeEntity entitys : organizeEntities) {
                    UserByRoleVO vo = new UserByRoleVO();
                    vo.setId(entitys.getId());
                    vo.setType(entitys.getCategory());
                    vo.setFullName(entitys.getFullName());
                    if ("department".equals(entitys.getCategory())) {
                        vo.setIcon("icon-ym icon-ym-tree-department1");
                    } else {
                        vo.setIcon("icon-ym icon-ym-tree-organization3");
                    }
                    vo.setHasChildren(true);
                    vo.setIsLeaf(false);
                    vo.setEnabledMark(entitys.getEnabledMark());
                    jsonToList.add(vo);
                }
            }
            return ActionResult.success(jsonToList);
        }

        // 判断是否有父级
        Set<OrganizeEntity> set = new HashSet<>(16);
        for (OrganizeEntity entity : orgEntityList) {
            List<OrganizeEntity> collect1 = orgEntityList.stream().filter(t -> !entity.getId().equals(t.getId()) && entity.getOrganizeIdTree().contains(t.getOrganizeIdTree())).collect(Collectors.toList());
            set.addAll(collect1);
        }
        List<OrganizeEntity> list = new ArrayList<>(set);
        // 从list中一处已经有的
        List<OrganizeEntity> list1 = new ArrayList<>(list);
        for (OrganizeEntity organizeEntity : list) {
            List<OrganizeEntity> collect1 = list.stream().filter(t -> !organizeEntity.getId().equals(t.getId()) && t.getOrganizeIdTree().contains(organizeEntity.getId())).collect(Collectors.toList());
            list1.removeAll(collect1);
        }
        list = list1;
        // 纯断层的
        List<OrganizeEntity> list2 = new ArrayList<>(orgEntityList);
        for (OrganizeEntity organizeEntity : orgEntityList) {
            if (list.stream().filter(t -> organizeEntity.getOrganizeIdTree().contains(t.getId())).count() > 0) {
                list2.remove(organizeEntity);
            }
        }
        list.addAll(list2);
        for (OrganizeEntity organizeEntity : list) {
            if (organizeEntity != null && organizeEntity.getEnabledMark() == 1) {
                UserByRoleVO userByRoleVO = new UserByRoleVO();
                userByRoleVO.setId(organizeEntity.getId());
                userByRoleVO.setType(organizeEntity.getCategory());
                String orgName = organizeService.getFullNameByOrgIdTree(organizeEntity.getOrganizeIdTree(), "/");
                userByRoleVO.setFullName(orgName);
                if ("department".equals(organizeEntity.getCategory())) {
                    userByRoleVO.setIcon("icon-ym icon-ym-tree-department1");
                } else {
                    userByRoleVO.setIcon("icon-ym icon-ym-tree-organization3");
                }
                userByRoleVO.setHasChildren(true);
                userByRoleVO.setIsLeaf(false);
                userByRoleVO.setEnabledMark(organizeEntity.getEnabledMark());
                jsonToList.add(userByRoleVO);
            }
        }
        return ActionResult.success(jsonToList);
    }

    /**
     * 获取我的下属(不取子集)
     *
     * @param page 页面信息
     * @return ignore
     */
    @ApiOperation("获取我的下属(不取子集)")
    @PostMapping("/getSubordinates")
    public ActionResult<List<UserIdListVo>> getSubordinates(@RequestBody Page page) {
        List<UserEntity> list = userService.getListByManagerId(userProvider.get().getUserId(), page.getKeyword());
        for (UserEntity entity : list) {
            entity.setRealName(entity.getRealName() );
        }
        List<UserIdListVo> jsonToList = JsonUtil.getJsonToList(list, UserIdListVo.class);
        return ActionResult.success(jsonToList);
    }

    /**
     * 导出excel
     *
     * @param dataType   导出方式
     * @param pagination 分页
     * @return ignore
     */
    @ApiOperation("导出excel")
    @GetMapping("/ExportExcel")
    public ActionResult<DownloadVO> Export(String dataType, String selectKey, PaginationUser pagination) {
        // 导出
        DownloadVO vo = userService.exportExcel(dataType, selectKey, pagination);
        return ActionResult.success(vo);
    }

    /**
     * 模板下载
     *
     * @return ignore
     */
    @ApiOperation("模板下载")
    @GetMapping("/TemplateDownload")
    public ActionResult<DownloadVO> TemplateDownload() {
        UserInfo userInfo = userProvider.get();
        DownloadVO vo = DownloadVO.builder().build();
        try {
            vo.setName("用户信息.xlsx");
            vo.setUrl(UploaderUtil.uploaderFile("/api/file/DownloadModel?encryption=", userInfo.getId() + "#" + "用户信息" +
                    ".xlsx" + "#" + "Temporary"));
        } catch (Exception e) {
            log.error("信息导出Excel错误:" + e.getMessage());
        }
        return ActionResult.success(vo);
    }


    /**
     * 导入数据
     *
     * @return ignore
     */
    @ApiOperation("导入数据")
    @PostMapping("/ImportData")
    public ActionResult<UserImportVO> ImportData(@RequestBody UserExportVO data) throws PermissionException {
        List<UserExportVO> dataList = JsonUtil.getJsonToList(data.getList(), UserExportVO.class);
        //导入数据
        UserImportVO result = userService.importData(dataList);
        return ActionResult.success(result);
    }

    /**
     * 导出错误报告
     *
     * @return ignore
     */
    @ApiOperation("导出错误报告")
    @PostMapping("/ExportExceptionData")
    public ActionResult<DownloadVO> exportExceptionData(@RequestBody UserExportVO data) {
        List<UserExportVO> dataList = JsonUtil.getJsonToList(data.getList(), UserExportVO.class);
        //生成Excel
        DownloadVO vo = userService.exportExceptionData(dataList);
        return ActionResult.success(vo);
    }

    /*= different =*/

    /**
     * 上传文件(excel)
     *
     * @return ignore
     */
    @ApiOperation("上传文件")
    @PostMapping("/Uploader")
    public ActionResult<Object> Uploader() {
        List<MultipartFile> list = UpUtil.getFileAll();
        MultipartFile file = list.get(0);
        if (file.getOriginalFilename().endsWith(".xlsx") || file.getOriginalFilename().endsWith(".xls")) {
            String filePath = XSSEscape.escape(configValueUtil.getTemporaryFilePath());
            String fileName = XSSEscape.escape(RandomUtil.uuId() + "." + UpUtil.getFileType(file));
            //上传文件
            FileUtil.upFile(file, filePath, fileName);
            try {
                UploadUtil.uploadFile(configValueUtil.getFileType(), filePath + fileName, FileTypeEnum.TEMPORARY, fileName);
            } catch (IOException e) {
                log.error("上传文件失败：" + e.getMessage());
            }
            DownloadVO vo = DownloadVO.builder().build();
            vo.setName(fileName);
            return ActionResult.success(vo);
        } else {
            return ActionResult.fail("选择文件不符合导入");
        }
    }

    /**
     * 导入预览
     *
     * @return
     */
    @ApiOperation("导入预览")
    @GetMapping("/ImportPreview")
    public ActionResult<Map<String, Object>> ImportPreview(String fileName) {
        String filePath = configValueUtil.getTemporaryFilePath();
        UploadUtil.downToLocal(configValueUtil.getFileType(), fileName, FileTypeEnum.TEMPORARY, filePath);
        File temporary = new File(XSSEscape.escapePath(filePath + fileName));
        // 得到数据
        List<UserExportVO> personList = ExcelUtil.importExcel(temporary, 0, 1, UserExportVO.class);
        // 预览数据
        Map<String, Object> map = userService.importPreview(personList);
        return ActionResult.success(map);
    }

    /**
     * 根据角色ID获取所属组织的所有成员
     *
     * @return
     */
    @ApiOperation("根据角色ID获取所有成员")
    @GetMapping("/getUsersByRoleId")
    public ActionResult getUsersByRoleId(PaginationUser pagination) {
        List<UserEntity> userList = new ArrayList<>();
        if (roleService.getInfo(pagination.getRoleId()).getGlobalMark() == GlobalMarkEnum.NOT_ORGANIZE.getCode()) {
            userList.addAll(userService.getList(pagination, null, false));
        } else {
            // 根据roleId获取所有组织
            userService.getListByRoleId(pagination.getRoleId()).forEach(u -> {
                userList.add(userService.getInfo(u.getId()));
            });
        }
        // 去重
        List<UserEntity> afterUserList = userList.stream().distinct().collect(Collectors.toList());
        if (StringUtils.isNotEmpty(pagination.getKeyword())) {
            afterUserList = afterUserList.stream().filter(t -> t.getRealName().contains(pagination.getKeyword()) || t.getAccount().contains(pagination.getKeyword())).collect(Collectors.toList());
        }
        PaginationVO paginationVO = JsonUtil.getJsonToBean(pagination, PaginationVO.class);
        return ActionResult.page(afterUserList, paginationVO);
    }

    /**
     * 根据用户id获取组织树，并去重装进集合
     */
    @GetMapping("/getOrganizeTreeById/{userId}")
    public ActionResult getOrganizeTreeById(@PathVariable("userId") String userId) {
        UserInfo userInfo = userProvider.get();
        List<String> orgIdString = new ArrayList<>();
        List<OrganizeEntity> allOrgByUserId = organizeService.getAllOrgByUserId(userId);
        List<String> collect1 = allOrgByUserId.stream().map(OrganizeEntity::getOrganizeIdTree).collect(Collectors.toList());

        //显示当前用户默认组织
        for (String s : collect1) {
            if(s.contains(userInfo.getOrganizeId())){
                String[] split = s.split(",");
                orgIdString.addAll(Arrays.asList(split));
            }

        }
        List<String> collect = orgIdString.stream().distinct().collect(Collectors.toList());

        return ActionResult.success(collect);

    }

    public List<String> getOrganizeTreeByUserId(String userId) {
        List<String> orgIdString = new ArrayList<>();
        List<OrganizeEntity> allOrgByUserId = organizeService.getAllOrgByUserId(userId);
        List<String> collect1 = allOrgByUserId.stream().map(OrganizeEntity::getOrganizeIdTree).collect(Collectors.toList());
        if (ObjectUtil.isNotEmpty(collect1)) {
            for (String s : collect1) {
                String[] split = s.split(",");
                if (split.length >= 1) {
                    orgIdString.add(split[1]);
                }
            }
        }
        return orgIdString.stream().distinct().collect(Collectors.toList());
    }

}
